//
//  CommentView.swift
//  QKYC
//
//  Created by 陈鹏飞 on 2019/4/16.
//  Copyright © 2019 zhan. All rights reserved.
//
import Foundation
import IQKeyboardManagerSwift
open class CommentView: UIView ,UITextFieldDelegate,UITextViewDelegate{
    
    
    public var textViewPlaceHolder:String = "说点什么吧~"{
        didSet{
            textView.myPlaceholder = textViewPlaceHolder
        }
    }
    
    
    public var textViewText:String = ""{
        didSet{
            textView.text=textViewText
        }
    }
    
    
    ///评论的输入框
    public lazy var textView: ZAIPlaceholderTextView = {
        let textView = ZAIPlaceholderTextView()
        textView.delegate=self
        textView.backgroundColor = UIColor.white
        textView.myPlaceholderColor = UIColor.RGB(r: 152, g: 154, b: 162)
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.contentInset=UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        textView.layer.cornerRadius=5
        textView.layer.masksToBounds=true
        textView.keyboardType = .default
        textView.returnKeyType = .done
        textView.inputAccessoryView = nil
        return textView
    }()
    
    
    ///评论提交按钮
    public lazy var commentButton: UIButton = {
        let commentButton = UIButton()
        commentButton.setTitle("发布", for: .normal)
        commentButton.layer.cornerRadius = 5
        commentButton.layer.masksToBounds = true
        commentButton.backgroundColor = UIColor.white
        commentButton.setTitleColor(UIColor.RGB(r: 64, g: 213, b: 194), for: .normal)
        commentButton.titleLabel?.textAlignment = .center
        commentButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        commentButton.addTarget(self, action: #selector(gotoComment), for: .touchUpInside)
        return commentButton
    }()
    
    
    ///父组件的顶部高度
    public var superTopHeight:CGFloat=0.0
    
    public var keyBordTopY:CGFloat = 0{
        didSet{
            keyBordHeightChange?(keyBordTopY)
        }
    }
    
    ///键盘显示与隐藏状态
    private var keyBordShowStatus:((Bool)->())?
    public func postKeyBordShowStatus(withBlock block:((Bool)->())?)  {
        keyBordShowStatus=block
    }
    
    
    ///键盘出现的时候
    private var keyBordHeightChange:((CGFloat)->())?

    
    public func postKeyBordChange(with block:((CGFloat)->())?)  {
        keyBordHeightChange=block
    }
  
    ///外面控制键盘是否隐藏
    public var textViewIsEditing:Bool = false{
        didSet{
            if textViewIsEditing{
                textView.becomeFirstResponder()
            }else{
                textView.resignFirstResponder()
            }
        }
    }
    
    ///临时保存点击的位置
    public var tempSaveClickIndex:IndexPath = IndexPath(row: -1, section: -1)

    //mark: 记录UITextView的原始高度
    private var textViewHeight: CGFloat = 0
    
    ///点击发送按钮的回调
    private var postCommentBlock:((String) ->())?
    
    ///保存输入框的高度
    private var tempTextViewHeight:CGFloat = 0
    
    ///记录scrollview修改前的位置
    public var tempSaveScrollViewY:CGFloat = 0
    
    public func postCommentProcessBlock(withBlock block:((String) ->())?)  {
        postCommentBlock = block
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.white
        setSubViews()
        //获取原始位置
        textViewHeight = self.frame.origin.y
        tempTextViewHeight = self.frame.size.height
        //注册监听
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    private func setSubViews() {
        self.addSubview(commentButton)
        self.addSubview(textView)
        commentButton.snp.makeConstraints { (make) in
            make.width.equalTo(44*PionWidth)
            make.right.equalTo(self.snp.right).offset(-15*PionWidth)
            make.centerY.equalTo(self.snp.centerY)
            make.height.equalTo(38*PionHeight)
        }
        textView.snp.makeConstraints { (make) in
            make.right.equalTo(commentButton.snp.left).offset(-10*PionWidth)
            make.height.equalTo(38*PionHeight)
            make.left.equalTo(self.snp.left).offset(15*PionWidth)
            make.centerY.equalTo(self.snp.centerY)
        }
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    //mark: 当键盘显示时
    @objc fileprivate func keyBoardWillShow(notification: NSNotification) {
        keyBordShowStatus?(true)
        let userInfo: NSDictionary = notification.userInfo! as NSDictionary
        let value = userInfo.object(forKey: UIResponder.keyboardFrameEndUserInfoKey)
        let keyboardRect = (value as AnyObject).cgRectValue
        UIView.animate(withDuration: 0.25) {[weak self] in
            self!.frame.origin.y = ScreenH - (keyboardRect?.height)! - self!.frame.height - self!.superTopHeight
            self!.frame.size.height=self!.tempTextViewHeight+2*PionHeight
            self!.keyBordTopY = self!.frame.origin.y
        }
    }
    
    //mark: 当键盘隐藏时
    @objc fileprivate func keyBoardWillHide(notification: NSNotification) {
        keyBordShowStatus?(false)
        textViewPlaceHolder="说点什么吧~"
        textViewText=""
        UIView.animate(withDuration: 0.25, animations: {
            var frame = self.frame
            frame.origin.y = self.textViewHeight
            self.frame = frame
            self.keyBordHeightChange?(-1)
        }) {[weak self] (flag) in
            if flag{
                self?.setNoText()
                self?.tempSaveClickIndex=IndexPath(row: -1, section: -1)
            }
        }
    }
    
   
    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n"{
            textViewIsEditing=false
        }
        return true
    }
    
    ///重置输入的内容
    private func setNoText() {
        textView.text = ""
    }
    
    public func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > 200{
            textView.text = NSString(string: textView.text).substring(to: 200)
        }
    }
    
    /// 发送按钮点击
    @objc fileprivate func gotoComment(){
        postCommentBlock?(textView.text)
    }
    
    
    deinit {
        print("评论输入销毁")
        NotificationCenter.default.removeObserver(self)
    }
}

